<?php
// +----------------------------------------------------------------------
// | Author: wyd
// +----------------------------------------------------------------------
// | Date: 2025/7/8
// +----------------------------------------------------------------------

// [ 应用入口文件 ]
declare(strict_types=1);

use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Http\Server;


//若某个类明明存在却提示not found  执行 composer dump-auto
require_once __DIR__ . '/../vendor/autoload.php';

require_once __DIR__ .'/app/config/define.php';

\My\core\BeanFactory::init();
$dispatcher = \My\core\BeanFactory::getBean(\My\core\frame\RouterCollector::class)->getDispatcher();


$http = new Server('0.0.0.0', 9501);

$http->on('Request', function (Request $request, Response $response) use ($dispatcher) {
    $myRequest = \My\core\http\Request::init($request);
    $myResponse = \My\core\http\Response::init($response);
    $routeInfo = $dispatcher->dispatch($myRequest->method(), $myRequest->uri());
    //var_dump($routeInfo);
    switch ($routeInfo[0]) {
        //$routeInfo,[]
        case FastRoute\Dispatcher::NOT_FOUND:
            // ... 404 Not Found
            $response->end();
           // $response->status(404);
           // $response->end();
            break;
        case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
            $allowedMethods = $routeInfo[1];
            $response->status(405);
            $response->end();
            // ... 405 Method Not Allowed
            break;
        case FastRoute\Dispatcher::FOUND:
            $handler = $routeInfo[1];       //是路由的处理程序，也就是在addRoute时传入的第三个参数（可以是闭包、函数名、类方法等）
            // $routeInfo[2];       是一个关联数组，包含路由中的命名参数（例如从路由模式中提取的）
            //例如，如果您的路由模式是'/user/{id}'，并且当前请求的URL是'/user/123'，那么$routeInfo[2]就是['id' => '123']。
            //$response->end($handler($routeInfo[2],[$myRequest]));  //第二个参数是扩展参数

            $myResponse->setBody($handler($routeInfo[2],[$myRequest]));
            $myResponse->end();

            break;
    }
});

$http->start();
